<?php
require_once "db.php";
session_start();
$movie = db_escape($_POST['movie']);
$rating = db_escape($_POST['rate']);
$account = $_SESSION['uid'];

$write_rate_query_text = "UPDATE reservations SET personal_rating='$rating' WHERE accounts_idaccounts='$account' AND movies_idmovies='$movie'";
$write_rate_query = db_query($write_rate_query_text);

$update_overal_rating_query_text = "SELECT personal_rating FROM reservations WHERE movies_idmovies='$movie' AND personal_rating!=0 GROUP BY accounts_idaccounts";
$update_overal_rating_query = db_query($update_overal_rating_query_text);
$sum = 0;
while ($row = mysqli_fetch_assoc($update_overal_rating_query)){
	$sum += $row['personal_rating'];
}
$num_of_accounts = mysqli_num_rows($update_overal_rating_query);
$movie_rating = $sum/$num_of_accounts;
$update_query_text = "UPDATE movies SET overal_rating = '$movie_rating' WHERE idmovies='$movie'";
$update = db_query($update_query_text);
echo "Your rating was saved. Thank you!";

